const gulp = require("gulp");
const connect = require("gulp-connect");
const concat = require("gulp-concat");
var sass = require('gulp-sass');
sass.compiler = require('node-sass');

const scriptsJson = require("./conf/index").scripts;
const scssJson = require("./conf/index").scss;

let scriptsTaskArray = [];
let scssTaskArray = [];

// 功能定义区

/**
 * @function init 初始化功能 , 编列了scripts路径还有创建了 scripts 指令;
 * @function watchScripts 根据scripts对象实现的 watch 监听封装
 * @function mergeMyScripts 根据scripts 对象实现的scripts指令拆分,文件合并
 * 
 */
function init(){
    mergeMyScripts(scriptsJson);
    mergeMyScss(scssJson);
}

function watchScripts(json){
    for(let attr in json){
        gulp.watch(json[attr].src+"*.js",["scripts-"+attr]);
    }
}

function watchScss(json){
    for(let attr in json){
        gulp.watch(json[attr].src+"*.+(scss|sass)",["scss-"+attr]);
    }
}

function mergeMyScripts(json){
    for(let attr in json){
        scriptsTaskArray.push("scripts-"+attr);
        gulp.task("scripts-"+attr,()=>{
            return gulp.src([scriptsJson[attr].src+"*.js"])
                        .pipe(concat(attr+".js"))
                        .pipe(gulp.dest("./dev/scripts"))
                        .pipe(connect.reload());
        })
    }
}

function mergeMyScss(json){
    for(let attr in json){
        scssTaskArray.push("scss-"+attr);
        gulp.task("scss-"+attr,()=>{
            return gulp.src([scssJson[attr].src+"*.+(scss|sass)"])
                        .pipe(concat(attr+".scss"))
                        .pipe(sass())
                        .pipe(gulp.dest("./dev/scss"))
                        .pipe(connect.reload());
        })
    }
}

//指令定义区

/**
 * @task html :  转存html
 * @task connect : 服务器配置
 * @task watch : 监听
 * @task default : 自动开启环境
 * 
 */

 gulp.task("html",()=>{
    return gulp.src(["./src/views/**/*.html"])
                .pipe(gulp.dest("./dev/views"))
                .pipe(connect.reload());
 });

 gulp.task("connect",()=>{
    connect.server({
        root: 'dev/views',
        livereload: true,
    });
 });

 gulp.task("watch",()=>{
    gulp.watch("./src/views/**/*.html", ["html"]);
    watchScripts(scriptsJson);
    watchScss(scssTaskArray);
 });

 gulp.task("images",()=>{
    return gulp.src("./src/images/**/*")
                .pipe(gulp.dest("./dev/images"));
 })

 gulp.task("scripts",scriptsTaskArray);
 gulp.task("scss",scssTaskArray);

 gulp.task("gulp-dev",["html","scripts","scss","images","connect","watch"]);

 init();

 require("./gulp-build")